﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ImageMagick;
using Module_Debug.socket;

namespace Module_Debug.VESADSCTool
{
    public partial class DSCToos : Form
    {
        public DSCToos()
        {
            InitializeComponent();
        }

        private void BmpLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.Filter = "图片(*.bmp *.jpg *.png)|*.jpg;*.png;*.jpeg;*.bmp|所有文件(*.*)|*.*";
            ofd.Title = "选择图片文件";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                listBox3_BMPFile.Items.Clear();
                string bfile = null;
                foreach (string file in ofd.FileNames)
                {
                    listBox3_BMPFile.Items.Add(file);
                    bfile = file;
                    btnConvert.Enabled = true;
                }
                if (bfile != null)
                {
                    txtbmpPath.Text = Path.GetDirectoryName(bfile);
                }
            }
            //----------------------------------------------
            listBox3_BMPFile.SelectedIndex =0;         

            //listBox3_BMPFile_SelectedIndexChanged(null, null);
        }
        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
        private void listBox3_BMPFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            string bpath = (string)listBox3_BMPFile.SelectedItem;
            FileStream fileStream = new FileStream(bpath, FileMode.Open, FileAccess.Read);
            try
            {
                pictureBox1.Image = Image.FromStream(fileStream);
                textBox1.Text = bpath;
                GetJpgSizeByMagickImage(bpath, out Size JpgSize, out double Wpx, out double Hpx);
                //---------------------
                int tep = JpgSize.Width;              
                //--------------------
                //if(rdoAutoWidth.Checked) { numBmpWidth.Value = JpgSize.Width; }
            }
            catch
            {
                pictureBox1.Image = null; textBox1.Text = "\r\n" + "---非标准图片，无法预览---\r\n";
            }
            fileStream.Close();
            fileStream.Dispose();
        }
        public static void GetJpgSizeByMagickImage(string JpgPath, out Size JpgSize, out double Wpx, out double Hpx)
        {
            try
            {
                MagickImageInfo image = new MagickImageInfo(JpgPath);
                int w = image.Width;//宽
                int h = image.Height;//高
                JpgSize = new Size(w, h);
                Wpx = image.Density.X;//分辨率
                Hpx = image.Density.Y;//分辨率
                if (image.Density.Units == DensityUnit.PixelsPerCentimeter)//判断分辨率单位
                {
                    Wpx *= 2.54;
                    Hpx *= 2.54;
                }
            }
            catch
            {
                JpgSize = new Size(0, 0);
                Wpx = 0; Hpx = 0;
            }
        }

        private void listBox3_BMPFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            else if (e.KeyCode == Keys.Delete)
            {
                if (listBox3_BMPFile.SelectedIndex < listBox3_BMPFile.Items.Count - 1)
                {
                    listBox3_BMPFile.Items.Remove(listBox3_BMPFile.SelectedItem);
                }
                else
                {
                    listBox3_BMPFile.SelectedIndex = 0;
                }
            }
        }   //删除误选择的文件

        private void btnSetOutputPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog ofd = new FolderBrowserDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (txtOutFolder.Text != "")
                {
                    DSCOutPath = ofd.SelectedPath + "\\" + txtOutFolder.Text + "\\";
                }
            }
        }  //设定输出目录名称   
        string PicFullPath = @"D:\users\10802400.bmp";
        string PicDirectoryName = @".\", PicFileNameWithoutExtension = "abc", DSCOutPath = @".\output\";
        int SLICE_WIDTH = 612, SLICE_HEIGHT = 24, DSC_VERSION = 1;
        delegate void SetTextCallback(string text);
        public void SetText(string text)
        {
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.AppendText(text);
                //this.textBox1.Refresh();
            }
        }

        private void DSC_Process()
        {

            string tcmdpSW = "-OSLICE_WIDTH " + SLICE_WIDTH;
            tcmdpSW = "\"" + tcmdpSW + "\"";
            string tcmdpSH = "-OSLICE_HEIGHT " + SLICE_HEIGHT;
            tcmdpSH = "\"" + tcmdpSH + "\"";
            

            System.Diagnostics.Process p0 = new System.Diagnostics.Process();
            p0.StartInfo.FileName = @".\esa_tool\Resource\DSCtools\nconvert.exe";
            PicFullPath = "\"" + PicFullPath + "\"";
            //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp
            //{   //10bpc_8bpp
            //    p0.StartInfo.Arguments = @"-out  dpx  -o .\esa_tool\Resource\DSCtools\dsc_bmp_in.dpx " + PicFullPath;
            //}
            //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
            //{
            //    p0.StartInfo.Arguments = @"-out  dpx  -o .\esa_tool\Resource\DSCtools\dsc_bmp_in.dpx " + PicFullPath;
            //}
            //else
            {
                //默认 8bpc-8bpp
                p0.StartInfo.Arguments = @"-out  dpx  -o .\esa_tool\Resource\DSCtools\dsc_bmp_in.dpx " + PicFullPath;
            }

            p0.Start();
            p0.WaitForExit();
            p0.Close();
            // ..\..\dsc.exe - F dsc_1_1.cfg "-OSLICE_WIDTH %4" "-OSLICE_HEIGHT %2" "-OFUNCTION 1" "-ODSC_VERSION_MINOR %3"..\..\dsc.exe - F dsc_1_1.cfg "-OSLICE_WIDTH %4" "-OSLICE_HEIGHT %2" "-OFUNCTION 2" "-ODSC_VERSION_MINOR %3"
            System.Diagnostics.Process p1 = new System.Diagnostics.Process();

            //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp   rc_10bpc_8bpp
            //{   //10bpc_8bpp
            //    p1.StartInfo.WorkingDirectory = Application.StartupPath + @"\esa_tool\Resource\DSCtools";
            //}
            //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
            //{
            //    p1.StartInfo.WorkingDirectory = Application.StartupPath + @"\esa_tool\Resource\DSCtools";
            //}
            //else
            {
                p1.StartInfo.WorkingDirectory = Application.StartupPath + @"\esa_tool\Resource\DSCtools";
            }

            if (numDSCVer.Value == 1)//vesa DSC 1.1
            {
                p1.StartInfo.FileName = Application.StartupPath + @"\esa_tool\Resource\DSCtools\DSC1p2Ver167.exe";
                
                p1.StartInfo.Arguments = @"-F  dsc_1_1.cfg  " + tcmdpSW + " " + tcmdpSH + " " + @" ""-OFUNCTION 1"" " ;
            }
            else if (numDSCVer.Value == 2) //vesa DSC 1.2a
            {
                p1.StartInfo.FileName = Application.StartupPath + @"\esa_tool\Resource\DSCtools\DSC1p2Ver167.exe";
               
                p1.StartInfo.Arguments = @"-F  dsc_1_2.cfg  " + tcmdpSW + " " + tcmdpSH + " " + @" ""-OFUNCTION 1"" " ;
            }
            else //Legacy vesa DSC 1.1
            {
                p1.StartInfo.FileName = Application.StartupPath + @"\esa_tool\Resource\DSCtools\DSC1p1Ver131a.exe";

                p1.StartInfo.Arguments = @"-F  dsc_1_1_Legacy.cfg  " + tcmdpSW + " " + tcmdpSH + " " + @" ""-OFUNCTION 1"" ";
            }

            if (chkDSCoutlog.Checked)
            {
                p1.Start();
            }
            else
            {
                //是否使用操作系统shell启动
                p1.StartInfo.UseShellExecute = false;
                // 接受来自调用程序的输入信息
                //p1.StartInfo.RedirectStandardInput = true;
                //输出信息
                p1.StartInfo.RedirectStandardOutput = true;
                // 输出错误
                p1.StartInfo.RedirectStandardError = true;
                //不显示程序窗口
                p1.StartInfo.CreateNoWindow = true;
                //应该触发退出事件
                p1.EnableRaisingEvents = true;
                //程序退出事件
                p1.Exited += (s, e) =>
                {
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "转换完成，DSC程序退出");
                };
                //程序输出消息事件
                p1.OutputDataReceived += (o, e) =>
                {
                    if (string.IsNullOrWhiteSpace(e?.Data))
                    {
                        return;
                    }
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "程序执行消息：" + e.Data);
                };
                p1.Start();
                p1.BeginOutputReadLine();
            }
            //等待程序执行完退出进程
            p1.WaitForExit();

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            string strOuput = "";
            if (chkoutBMP.Checked)
            {               

                //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp   rc_10bpc_8bpp
                //{   //10bpc_8bpp
                //    //p.StandardInput.WriteLine(@".\esa_tool\Resource\DSCtools\lua.exe " + @".\esa_tool\Resource\DSCtools\dsc2bmp.lua  .\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc" + "&exit");
                //    ConvertDscToBmp(@".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc", @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp");
                //}
                //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
                //{
                //    //p.StandardInput.WriteLine(@".\esa_tool\Resource\DSCtools\lua.exe " + @".\esa_tool\Resource\DSCtools\dsc2bmp.lua  .\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc" + "&exit");
                //    ConvertDscToBmp(@".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc", @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp");
                //}
                //else
                {
                    //p.StandardInput.WriteLine(@".\esa_tool\Resource\DSCtools\lua.exe " + @".\esa_tool\Resource\DSCtools\dsc2bmp.lua  .\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc" + "&exit");
                    ConvertDscToBmp(@".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc", @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp");
                }
            }
            textBox1.Text += "\r\nDone....";
            #region   //删除无用的dpx文件
            //------------------------------------------------------------------------------------------------------
            // System.Diagnostics.Process p = new System.Diagnostics.Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = "cmd.exe";
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardInput = true;
            //输出信息
            p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            //p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            //启动程序
            p.Start();
            //向cmd窗口发送输入信息

            //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp   rc_10bpc_8bpp
            //{   //10bpc_8bpp
            //    p.StandardInput.WriteLine("del " + @".\esa_tool\Resource\DSCtools\*.dpx" + "&exit");
            //}
            //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
            //{
            //    p.StandardInput.WriteLine("del " + @".\esa_tool\Resource\DSCtools\*.dpx" + "&exit");
            //}
            //else
            {
                p.StandardInput.WriteLine("del " + @".\esa_tool\Resource\DSCtools\*.dpx" + "&exit");
            }


            p.StandardInput.AutoFlush = true;
            //获取输出信息
            strOuput = p.StandardOutput.ReadToEnd();
            //等待程序执行完退出进程
            p.WaitForExit();
            Console.WriteLine(strOuput);
            p.Close();
            #endregion
            #region  //把图放在指定的位置
            string path = DSCOutPath;
            try
            {
                // Determine whether the directory exists.
                if (Directory.Exists(path))
                {
                    Console.WriteLine("That path exists already.");
                }
                else
                {
                    // Try to create the directory.
                    DirectoryInfo di = Directory.CreateDirectory(path);
                    Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));

                    //// Delete the directory.
                    //di.Delete();
                    //Console.WriteLine("The directory was deleted successfully.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
            try
            {
                DateTime currentTime = new System.DateTime();
                currentTime = System.DateTime.Now;
                int sec = currentTime.Second;
                int minute = currentTime.Minute;
                string oldStr = "";
                string oldStr2 = "";

                //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp   rc_10bpc_8bpp
                //{   //10bpc_8bpp
                //    oldStr = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc";
                //    oldStr2 = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp";
                //}
                //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
                //{
                //    oldStr = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc";
                //    oldStr2 = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp";
                //}
                //else
                {
                    oldStr = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc";
                    oldStr2 = @".\esa_tool\Resource\DSCtools\dsc_bmp_in.dsc.bmp";
                }


                // 新文件名
                string newStr = "";
                string newStr2 = "";
                if (chkAddtimeflag.Checked)
                {
                    newStr = DSCOutPath + PicFileNameWithoutExtension + "_" + minute + sec + ".dsc";
                }
                else
                {
                    newStr = DSCOutPath + PicFileNameWithoutExtension + ".dsc";
                }
                // 改名方法
                FileInfo fi = new FileInfo(oldStr);
                fi.CopyTo(newStr, true);//可覆盖现有文件
                //fi.MoveTo((newStr));
                if (chkoutBMP.Checked)
                {
                    if (chkAddtimeflag.Checked)
                    {
                        newStr2 = DSCOutPath + PicFileNameWithoutExtension + "_" + minute + sec + ".dsc.bmp";
                    }
                    else
                    {
                        newStr2 = DSCOutPath + PicFileNameWithoutExtension + ".dsc.bmp";
                    }
                    fi = new FileInfo(oldStr2);
                   // fi.MoveTo((newStr2));
                    fi.CopyTo(newStr2, true);//可覆盖现有文件

                    teppath = newStr2;
                }
            }
            catch
            {
                MessageBox.Show("转换失败.......", "系统提示：");
            }
            #endregion
        }
        string teppath = "";
        private void btnConvert_Click(object sender, EventArgs e)
        {
            string filePath = "";
            if (listBox3_BMPFile.Items.Count > 0)
            {
                //MessageBox.Show("转换开始，请点击“确定”并耐心等候转换完成的提示信息", "系统提示：");
                int iCount = listBox3_BMPFile.Items.Count - 1;
                for (int i = 0; i <= iCount; i++)
                {
                    listBox3_BMPFile.SelectedIndex = i;
                    filePath = listBox3_BMPFile.Items[i].ToString();
                    textBox1.Text = filePath;
                    PicDirectoryName = Path.GetDirectoryName(filePath) + "\\";
                    PicFileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                    DSCOutPath = Path.GetDirectoryName(filePath) + @"\DSCoutput\";
                    PicFullPath = filePath;
                    SLICE_WIDTH = (int)numSliceWidth.Value;
                    SLICE_HEIGHT = (int)numSliceHeight.Value;
                    DSC_VERSION = (int)numDSCVer.Value;
                    #region                   //-----------给一个安慰信息-------
                    if (listBox3_BMPFile.Items.Count == 1)
                    {
                        pBar1.Value = 50;
                    }
                    else
                    {
                        pBar1.Value = 100 * (i + 1) / (iCount + 2);
                    }
                    #endregion //-----------给一个安慰信息-------
                    DSC_Process();
                }
                pBar1.Value = 100;
                MessageBox.Show("转换完成，请到之前的图片目录下获取相关文件", "系统提示：");
                System.Diagnostics.Process.Start(DSCOutPath);
            }
            else
            {
                MessageBox.Show("请确认是否选中文件......", "系统提示：");
            }
        } //逐张图片转换
        private void Main_Load(object sender, EventArgs e)
        {
            //btnMainFormResize_Click(null,null);
            ReadWidthHeightDSCVer();
        }   //程序启动后自动加载之前的DSC切片参数
        List<string> lines;

        bool sizesmall = false;
        private void btnMainFormResize_Click(object sender, EventArgs e)
        {    //572-478  -->752-478
            if (sizesmall)
            {
                sizesmall = false;
                this.ClientSize = new System.Drawing.Size(736, 439);
                //btnMainFormResize.Text = "<-";
            }
            else
            {
                sizesmall = true;
                this.ClientSize = new System.Drawing.Size(556, 439);
                //btnMainFormResize.Text = "->";
            }

        }
        //string defaultfilePath;
        string PNGoutPath = @".\";
        private void btnSetoutpath_Click(object sender, EventArgs e)
        {
            btn0_255GrayCreat.Enabled = true;
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            //if (defaultfilePath == "")
            {
                fldb.ShowNewFolderButton = false;
                DialogResult res = fldb.ShowDialog();
                if (res != System.Windows.Forms.DialogResult.OK)
                {
                    MessageBox.Show("没选择任何文件夹.");
                    return;
                }
                //defaultfilePath = fldb.SelectedPath;
                PNGoutPath = fldb.SelectedPath;
                if (!Directory.Exists(PNGoutPath))
                {
                    MessageBox.Show("文件夹不存在.");
                    return;
                }
            }
            btnoutBMP.Enabled = true;
        }
        string tep_PNGoutPath;
        private void btnoutBMP_Click(object sender, EventArgs e)
        {
            #region   //画灰阶图
            Bitmap bm = new Bitmap((int)(numBmpWidth.Value), (int)(numBmpHeight.Value), PixelFormat.Format24bppRgb);//确定bmp的轮廓              
            Graphics g = Graphics.FromImage(bm);
            byte grayvalue = (byte)numBmpGray.Value;
            SolidBrush brush = new SolidBrush(Color.FromArgb(grayvalue, grayvalue, grayvalue));//设置笔刷的属性，颜色
            g.FillRectangle(brush, 0, 0, (int)(numBmpWidth.Value), (int)(numBmpHeight.Value));

            string graynum = numBmpGray.Value.ToString();
            Font myFont = new Font("微软雅黑", 24);//实例化Font对象 设置字号大
            SolidBrush brush1 = new SolidBrush(Color.FromArgb(0, 128, 0));//设置笔刷的属性，颜色 //字体属性
            g.DrawString(graynum, myFont, brush1, 100, 10);//绘制文本 （x,y）=  (100, j)字体起点

            this.pictureBox1.Image = (Image)bm;//读取bm到picturebox
            ///create_my_file();//创建文件夹
            if (rdoBMPFlag.Checked)
            {
                tep_PNGoutPath = PNGoutPath + "\\" + numBmpGray.Value.ToString() + @".bmp";
                bm.Save(tep_PNGoutPath, System.Drawing.Imaging.ImageFormat.Bmp);
            }
            else
            {
                tep_PNGoutPath = PNGoutPath + "\\" + numBmpGray.Value.ToString() + @".png";
                bm.Save(tep_PNGoutPath, System.Drawing.Imaging.ImageFormat.Png);
            }

            #endregion
            //MemoryStream aFile;
            //aFile = new MemoryStream();
            //bm.Save(aFile, System.Drawing.Imaging.ImageFormat.Bmp);
        }

        private void btnOpenPhgFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(PNGoutPath);
        }

        private void ReadWidthHeightDSCVer()
        {
            lines = new List<string>();
            FileStream fs = new FileStream(@".\esa_tool\WHV.cfg", FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string s;
            //读入文件所有行，存放到List<string>集合中
            while ((s = rd.ReadLine()) != null)
            {
                lines.Add(s);
            }
            rd.Close();
            fs.Close();
            string WW = "540", HH = "20", DSCVer = "2", bak0 = "0";
            if (lines.Count > 1)
            {
                WW = lines[0];
                HH = lines[1];
                DSCVer = lines[2];
                bak0 = lines[3];
            }
            numSliceWidth.Value = int.Parse(WW);
            numSliceHeight.Value = int.Parse(HH);
            numDSCVer.Value = int.Parse(DSCVer);
            //cBox_Dscmode.SelectedIndex = int.Parse(bak0);
        }  //读取基本配置以搭配上次生成DSC的设定
        private void WriteWidthHeightDSCVer()
        {
            string str = numSliceWidth.Value + "\r\n" + numSliceHeight.Value + "\r\n" + numDSCVer.Value + "\r\n" + "////Legacy" + "\r\n" + "bak1" + "\r\n" + "bak2" + "\r\n";
            StreamWriter sw = null; //文件流
            sw = new StreamWriter(@".\esa_tool\WHV.cfg", false, new System.Text.UTF8Encoding(false));  //utf8WithoutBom 重要，如果带BOM则导致DSC不能正常工作
            try
            {
                sw.Write(str);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流
                //MessageBox.Show("保存完成！", "系统提示：");
            }
            catch
            {
                MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
            }
        }   //保存基本配置

        private void btnOpenCFG_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@".\esa_tool\DSC压缩参数列表\");
        }

        private void btn0_255GrayCreat_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 256; i++)
            {
                numBmpGray.Value = i;
                btnoutBMP_Click(null, e);
            }
        }
        private void btnMerge_Click(object sender, EventArgs e)
        {
            bmpmerge(@"D:\users\图片\测试图库\10802400\m3\11_s1.bmp", @"D:\users\图片\测试图库\10802400\m3\11_s2.bmp");
        }
        private void btnSplit_Click(object sender, EventArgs e)
        {
            string filePath = "";
            string filePathtep1, filePathtep2= "";
            if (listBox3_BMPFile.Items.Count > 0)
            {
                //MessageBox.Show("转换开始，请点击“确定”并耐心等候转换完成的提示信息", "系统提示：");
                int iCount = listBox3_BMPFile.Items.Count - 1;
                for (int i = 0; i <= iCount; i++)
                {
                    listBox3_BMPFile.SelectedIndex = i;
                    filePath = listBox3_BMPFile.Items[i].ToString();
                    textBox1.Text = filePath;
                    PicDirectoryName = Path.GetDirectoryName(filePath) + "\\";
                    PicFileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                    DSCOutPath = Path.GetDirectoryName(filePath) + @"\DSCoutput\";
                    PicFullPath = filePath;
                    SLICE_WIDTH = (int)numSliceWidth.Value;
                    SLICE_HEIGHT = (int)numSliceHeight.Value;
                    DSC_VERSION = (int)numDSCVer.Value;
                    #region                   //-----------给一个安慰信息-------
                    if (listBox3_BMPFile.Items.Count == 1)
                    {
                        pBar1.Value = 50;
                    }
                    else
                    {
                        pBar1.Value = 100 * (i + 1) / (iCount + 2);
                    }
                    #endregion //-----------给一个安慰信息-------
                   string strpath1,strpath2="";
                    bmpsplit(filePath);
                    filePathtep1 = PicDirectoryName + PicFileNameWithoutExtension + "_s1.bmp";
                    PicFullPath = filePathtep1;
                    DSC_Process();
                    strpath1 = teppath;
                    filePathtep2 = PicDirectoryName + PicFileNameWithoutExtension + "_s2.bmp";
                    PicFullPath = filePathtep2;
                    DSC_Process();
                    strpath2 = teppath;
                    bmpmerge(strpath1, strpath2);
                }
                pBar1.Value = 100;
                MessageBox.Show("转换完成，请到之前的图片目录下获取相关文件", "系统提示：");
                System.Diagnostics.Process.Start(DSCOutPath);
            }
            else
            {
                MessageBox.Show("请确认是否选中文件......", "系统提示：");
            }
        }
        static void bmpmerge(string filepath1, string filepath2)
        {
            // 打开图片
            Bitmap image1 = new Bitmap(filepath1);
            Bitmap image2 = new Bitmap(filepath2);

            // 确保两幅图片的高度相同
            if (image1.Height != image2.Height)
            {
                throw new Exception("两幅图片的高度必须相同");
            }
            // 创建新的图片
            Bitmap newImage = new Bitmap(image1.Width + image2.Width, image1.Height,PixelFormat.Format24bppRgb);

            // 使用Graphics类拼接图片
            using (Graphics g = Graphics.FromImage(newImage))
            {
                // 绘制第一幅图片
                g.DrawImage(image1, 0, 0);
                // 绘制第二幅图片
                g.DrawImage(image2, image1.Width, 0);
            }

            // 获取原始文件的路径、文件名和扩展名
            string directory = Path.GetDirectoryName(filepath1);
            string filename1 = Path.GetFileNameWithoutExtension(filepath1);
            string filename2 = Path.GetFileNameWithoutExtension(filepath2);
            string extension = Path.GetExtension(filepath1);

            // 保存新的图片
            newImage.Save(Path.Combine(directory, filename1 + "_" + filename2 + extension), System.Drawing.Imaging.ImageFormat.Bmp);
        }
        static void bmpsplit(string filepath)
        {
            // 打开图片
            Bitmap original = new Bitmap(filepath);

            // 如果原始图片不是bmp格式，转换成bmp格式
            string extension = Path.GetExtension(filepath);
            if (extension.ToLower() != ".bmp")
            {
                original.Save(filepath, System.Drawing.Imaging.ImageFormat.Bmp);
            }

            // 计算新的宽度
            int width = original.Width / 2;

            // 创建新的图片
            Bitmap image1 = new Bitmap(width, original.Height, PixelFormat.Format24bppRgb);
            Bitmap image2 = new Bitmap(original.Width - width, original.Height, PixelFormat.Format24bppRgb);

            // 分割图片
            using (Graphics g = Graphics.FromImage(image1))
            {
                g.DrawImage(original, new Rectangle(0, 0, width, original.Height), new Rectangle(0, 0, width, original.Height), GraphicsUnit.Pixel);
            }
            using (Graphics g = Graphics.FromImage(image2))
            {
                g.DrawImage(original, new Rectangle(0, 0, original.Width - width, original.Height), new Rectangle(width, 0, original.Width - width, original.Height), GraphicsUnit.Pixel);
            }

            // 获取原始文件的路径和文件名
            string directory = Path.GetDirectoryName(filepath);
            string filename = Path.GetFileNameWithoutExtension(filepath);

            // 保存新的图片
            image1.Save(Path.Combine(directory, filename + "_s1.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
            image2.Save(Path.Combine(directory, filename + "_s2.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
        }

        private void btndsc2bmp_Click(object sender, EventArgs e)
        {
            string dsc_filepath = @"T:/rd_Smile_s1.dsc";
            string bmp_filepath = @"T:/dsc6.bmp";
            ConvertDscToBmp(dsc_filepath,  bmp_filepath);
        }

        public void ConvertDscToBmp(string dsc_filepath, string bmp_filepath)
        {
            const int BMP_HEADER_SIZE = 54;
            const int DSC_HEADER_SIZE = 132;

            using (BinaryReader dsc_file = new BinaryReader(File.Open(dsc_filepath, FileMode.Open)))
            using (BinaryWriter bmp_file = new BinaryWriter(File.Open(bmp_filepath, FileMode.Create)))
            {
                byte[] dsc_data = dsc_file.ReadBytes((int)dsc_file.BaseStream.Length);
                int height = dsc_data[11] + (dsc_data[10] << 8);
                int width = dsc_data[13] + (dsc_data[12] << 8);
                int tep = ((3 - width % 3) %3+ width);
                tep = (int)((4 - ((tep / 3) % 4))%4 + tep / 3);
                int bmpwidth = tep * 3;
                if (rdoAutoWidth.Checked) { bmpwidth = tep * 3; }
                else if (rdoMenuWidth.Checked)
                { bmpwidth =( int)(numOutBmpWidth.Value)*3; }
                int tep2 = (int)((width * height + (bmpwidth - 1)) / bmpwidth);
                int bmpheight = tep2 % 2 + tep2;               

                Console.WriteLine($"DSC image format {width} x {height}");
                Console.WriteLine($"BMP image format {bmpwidth/3} x {bmpheight}");
                int BMPpixtotal = bmpwidth * bmpheight;
                int BMPtotal = BMPpixtotal + BMP_HEADER_SIZE;
                // Resize dsc_data to BMPpixtotal
                Array.Resize(ref dsc_data, BMPpixtotal+ DSC_HEADER_SIZE);
                bmp_file.Write('B');
                bmp_file.Write('M');
                bmp_file.Write(BitConverter.GetBytes(BMPtotal));
                bmp_file.Write(new byte[] { 0x00, 0x00 });
                bmp_file.Write(new byte[] { 0x00, 0x00 });

                bmp_file.Write(new byte[] { 0x36, 0x00, 0x00, 0x00 });

                bmp_file.Write(new byte[] { 0x28, 0x00, 0x00, 0x00 });

                bmp_file.Write(BitConverter.GetBytes(bmpwidth / 3));
                bmp_file.Write(BitConverter.GetBytes(bmpheight));

                bmp_file.Write(new byte[] { 0x01, 0x00 });
                bmp_file.Write(new byte[] { 0x18, 0x00 });

                bmp_file.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 });

                bmp_file.Write(BitConverter.GetBytes(BMPpixtotal));

                bmp_file.Write(new byte[] { 0xc4, 0x0e, 0x00, 0x00 });
                bmp_file.Write(new byte[] { 0xc4, 0x0e, 0x00, 0x00 });

                bmp_file.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 });
                bmp_file.Write(new byte[] { 0x00, 0x00, 0x00, 0x00 });

                for (int i = bmpheight - 1; i >= 0; i--)
                {
                    for (int j = 0; j < bmpwidth; j += 3)
                    {
                        int index = (i * bmpwidth + j);
                        byte r = dsc_data[index + DSC_HEADER_SIZE];
                        byte g = dsc_data[index + 1 + DSC_HEADER_SIZE];
                        byte b = dsc_data[index + 2 + DSC_HEADER_SIZE];
                        bmp_file.Write(b);
                        bmp_file.Write(g);
                        bmp_file.Write(r);
                    }
                }
            }
        }

        private void numDSCVer_ValueChanged(object sender, EventArgs e)
        {
            if (numDSCVer.Value==0)
            {
                labDSCVer.Text = "旧版.Legacy DSCVer1.1";
            }
            else { labDSCVer.Text = "DSC Ver:1.67"; }
        }

        private void rdoMenuWidth_CheckedChanged(object sender, EventArgs e)
        {if(rdoMenuWidth.Checked == true)
            numOutBmpWidth.Enabled = true;
            else
            {
                numOutBmpWidth.Enabled = false;
            }
        }
        #region //V0045866专用

        private void UDP_receive_50ms_Tick(object sender, EventArgs e)
        {
            UDP_receive_50ms.Enabled = false;
            if (UDP_Rrogram.UDP_VESA_sign == 2)
            {
                UDP_Rrogram.UDP_BMP_out_path=UDP_in_VESA(UDP_Rrogram.UDP_BMP_in_path);
                UDP_Rrogram.UDP_VESA_sign = 3;
            }
            UDP_receive_50ms.Enabled = true;

        }
        private void checkBox_UDP_CheckedChanged(object sender, EventArgs e)
        {
            //UDP_VESA_sign=1开启等待，=2开始压缩，=3压缩完成，=1继续等待，=0不开压缩
            if (checkBox_UDP.Checked == true)
            {
                UDP_Rrogram.UDP_VESA_sign = 1;
                UDP_receive_50ms.Enabled = true;
                chkAddtimeflag.Checked = false;
            }
            else UDP_Rrogram.UDP_VESA_sign = 0;
        }
        private string UDP_in_VESA(string input_filePath)
        {
            string out_filePath;
            pBar1.Value = 0;
            PicDirectoryName = Path.GetDirectoryName(input_filePath) + "\\";
            PicFileNameWithoutExtension = Path.GetFileNameWithoutExtension(input_filePath);
            DSCOutPath = Path.GetDirectoryName(input_filePath) + @"\DSCoutput\";
            out_filePath = DSCOutPath + PicFileNameWithoutExtension + ".dsc.bmp";
            PicFullPath = input_filePath;
            SLICE_WIDTH = (int)numSliceWidth.Value;
            SLICE_HEIGHT = (int)numSliceHeight.Value;
            DSC_VERSION = (int)numDSCVer.Value;
            DSC_Process();
            pBar1.Value = 100;
            System.Diagnostics.Process.Start(DSCOutPath);
            textBox1.Text += "转化完成\r\n" + "路径:" + DSCOutPath.ToString() + "\r\n";
            return out_filePath;
        } //逐张图片转换
        #endregion



        bool editflag = false;
        private void btnEditDSCConfig_Click(object sender, EventArgs e)
        {
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Multiselect = false;
            //ofd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            //ofd.Title = "VESA DSC 参数";
            //if (ofd.ShowDialog() == DialogResult.OK)
            //{                
            //    foreach (string file in ofd.FileNames)
            //    {
            //    }
            //}
            string xbpc_xbppAddr;
            //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp
            //{   //10bpc_8bpp
            //    xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            //}
            //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
            //{
            //    xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            //}
            //else
            {
                //默认 8bpc-8bpp
                xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            }
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnDSCConfig":
                    {
                        if (!editflag)
                        {
                            this.textBox1.Location = new System.Drawing.Point(1, 6);
                            this.textBox1.Size = new System.Drawing.Size(427, 406);
                            editflag = true;
                            this.btnDSCConfig.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                            this.btnDSCConfig.ForeColor = System.Drawing.Color.Maroon;
                            btnDSCConfig.Text = "-保存-DSC配置";
                            btnCancelDscEdit.Enabled = true;
                            StreamReader streamReader = new StreamReader(xbpc_xbppAddr, Encoding.UTF8);
                            textBox1.Text = "//----请在此备注产品型号，以便于后续查看---\r\n" + streamReader.ReadToEnd();
                            streamReader.Close();
                        }
                        else
                        {
                            editflag = false;
                            this.textBox1.Location = new System.Drawing.Point(10, 340);
                            this.textBox1.Size = new System.Drawing.Size(320, 90);
                            this.btnDSCConfig.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                            this.btnDSCConfig.ForeColor = System.Drawing.Color.Black;
                            btnDSCConfig.Text = "编辑DSC配置文件";
                            btnCancelDscEdit.Enabled = false;
                            string str = "";
                            StreamWriter sw = null; //文件流
                            sw = new StreamWriter(xbpc_xbppAddr, false, new System.Text.UTF8Encoding(false));

                            try
                            {
                                str += textBox1.Text;
                                str += "\r\n";
                                sw.Write(str);
                                sw.Dispose(); //释放资源
                                sw.Close(); //关闭数据流
                                MessageBox.Show("T韬说处理完成！", "系统提示：");
                                textBox1.Clear();
                            }
                            catch
                            {
                                MessageBox.Show("唐T又说保存时发生错误，请再试！", "系统提示：");
                            }
                        }
                    }
                    break;
                case "btnCancelDscEdit":
                    {
                        editflag = false;
                        this.textBox1.Location = new System.Drawing.Point(10, 317);
                        this.textBox1.Size = new System.Drawing.Size(276, 92);
                        this.btnDSCConfig.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                        this.btnDSCConfig.ForeColor = System.Drawing.Color.Black;
                        btnDSCConfig.Text = "编辑DSC配置文件";
                        btnCancelDscEdit.Enabled = false;
                        textBox1.Clear();
                    }
                    break;
                default:
                    break;

            }
        }
        private void btnDSCcfgSaveAs_Click(object sender, EventArgs e)
        {
            WriteWidthHeightDSCVer();  //保存当前界面的参数
            string str = "";
            StreamReader streamReader = new StreamReader(@".\esa_tool\WHV.cfg", Encoding.UTF8);
            str = streamReader.ReadToEnd();
            streamReader.Close();
            string xbpc_xbppAddr = "";

            //if (cBox_Dscmode.SelectedIndex == 1)   //10bpc_8bpp
            //{   //10bpc_8bpp
            //    xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            //}
            //else if (cBox_Dscmode.SelectedIndex == 2)    //----占位备用
            //{
            //    xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            //}
            //else
            {
                //默认 8bpc-8bpp
                xbpc_xbppAddr = @".\esa_tool\Resource\DSCtools\rc_xbpc_xbpp.cfg";
            }

            streamReader = new StreamReader(xbpc_xbppAddr, Encoding.UTF8);
            str += "//-----------此处为分割线，勿动-----------\r\n" + streamReader.ReadToEnd();
            streamReader.Close();
            //-----------------------------
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";

            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, new System.Text.UTF8Encoding(false));
                try
                {
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("保存完成！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }   //保存完整配置文件方便后续调用
        private void btnReadDSCcfg_Click(object sender, EventArgs e)
        {
            lines = new List<string>();

            OpenFileDialog od = new OpenFileDialog();
            od.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";

            if (od.ShowDialog() == DialogResult.OK)
            {
                if (od.FileName == " ")
                {
                    return;
                }
                //FileStream fs = new FileStream(Application.StartupPath + "\\x_ViewTrix\\Fun1.txt", FileMode.Open)
                FileStream fs = new FileStream(od.FileName, FileMode.Open);
                StreamReader rd = new StreamReader(fs);
                string s;
                //读入文件所有行，存放到List<string>集合中
                while ((s = rd.ReadLine()) != null)
                {
                    lines.Add(s);
                }
                rd.Close();
                fs.Close();
                //第一行在txttip中显示
                string WW = "540", HH = "20", DSCVer = "2", bak0 = "0", bak1 = "0", bak2 = "0";
                if (lines.Count > 1)
                {
                    WW = lines[0];
                    HH = lines[1];
                    DSCVer = lines[2];
                    bak0 = lines[3];
                    bak1 = lines[4];
                    bak2 = lines[5];
                }
                numSliceWidth.Value = int.Parse(WW);
                numSliceHeight.Value = int.Parse(HH);
                numDSCVer.Value = int.Parse(DSCVer);
               
                //cBox_Dscmode.SelectedIndex = 0;
                WriteWidthHeightDSCVer();  //保存当前界面的参数
                btnEditDSCConfig_Click(btnDSCConfig, e);
                Thread.Sleep(200);
                Application.DoEvents();
                Thread.Sleep(200);
                Application.DoEvents();
                textBox1.Clear();
                Thread.Sleep(200);
                Application.DoEvents();
                for (int i = 6; i < lines.Count; i++)
                {
                    textBox1.Text += lines[i] + "\r\n";
                }
                Thread.Sleep(200);
                Application.DoEvents();
                btnEditDSCConfig_Click(btnDSCConfig, e);
                Thread.Sleep(200);
                Application.DoEvents();
            }
        }  //读取完整的配置文件

    }
}
